package handler

import (
	"context"
	"github.com/golang/protobuf/ptypes/empty"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	. "service/goods_srv/global"
	"service/goods_srv/model"
	"service/goods_srv/proto"
)

/*
//品牌分类
CategoryBrandList(context.Context, *CategoryBrandFilterRequest) (*CategoryBrandListResponse, error)
//通过category获取brands
GetCategoryBrandList(context.Context, *CategoryInfoRequest) (*BrandListResponse, error)
CreateCategoryBrand(context.Context, *CategoryBrandRequest) (*CategoryBrandResponse, error)
DeleteCategoryBrand(context.Context, *CategoryBrandRequest) (*emptypb.Empty, error)
UpdateCategoryBrand(context.Context, *CategoryBrandRequest) (*emptypb.Empty, error)
*/

// 创建商品分类和商品品牌的关联记录
func (g *GoodsServer) CreateCategoryBrand(c context.Context, r *proto.CategoryBrandRequest) (*proto.CategoryBrandResponse, error) {
	category := new(model.Category)
	category.ID = r.CategoryId
	result := DB.Where(category).First(category)
	if result.RowsAffected != 1 {
		return nil, status.Errorf(codes.NotFound, "CategoryId:商品分类不存在")
	}

	brand := new(model.Brands)
	brand.ID = r.BrandId
	result = DB.Where(brand).First(brand)
	if result.RowsAffected != 1 {
		return nil, status.Errorf(codes.NotFound, "BrandId:商品品牌不存在")
	}

	goodsCategoryBrand := &model.GoodsCategoryBrand{
		CategoryID: category.ID,
		BrandsID:   brand.ID,
	}
	result = DB.Create(goodsCategoryBrand)
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}

	categoryInfoResponse := &proto.CategoryInfoResponse{
		Id:             category.ID,
		Name:           category.Name,
		ParentCategory: category.ParentCategoryID,
		Level:          category.Level,
		IsTab:          category.IsTab,
	}
	brandInfoResponse := &proto.BrandInfoResponse{
		Id:   brand.ID,
		Name: brand.Name,
		Logo: brand.Logo,
	}

	return &proto.CategoryBrandResponse{
		Id:       goodsCategoryBrand.ID,
		Category: categoryInfoResponse,
		Brand:    brandInfoResponse,
	}, nil
}

// 获取分类-品牌对应关系表
func (g *GoodsServer) CategoryBrandList(c context.Context, r *proto.CategoryBrandFilterRequest) (*proto.CategoryBrandListResponse, error) {
	var total int64
	DB.Model(&model.GoodsCategoryBrand{}).Count(&total)

	var categoryBrandList []*model.GoodsCategoryBrand
	// Preload可在查询的同时根据外键查询到外键对应的记录，并将其解析到相应的结构体中
	// 例如加上Preload("Category")后，CategoryID对应的记录就会被解析到*Category中
	DB.Preload("Category").Preload("Brands").Scopes(Paginate(int(r.Pages), int(r.PagePerNums))).Find(&categoryBrandList)

	var categoryBrandResponse []*proto.CategoryBrandResponse
	for _, v := range categoryBrandList {
		categoryBrandResponse = append(categoryBrandResponse, &proto.CategoryBrandResponse{
			Id: v.ID,
			Category: &proto.CategoryInfoResponse{
				Id:             v.Category.ID,
				Name:           v.Category.Name,
				ParentCategory: v.Category.ParentCategoryID,
				Level:          v.Category.Level,
				IsTab:          v.Category.IsTab,
			},
			Brand: &proto.BrandInfoResponse{
				Id:   v.Brands.ID,
				Name: v.Brands.Name,
				Logo: v.Brands.Logo,
			},
		})
	}

	return &proto.CategoryBrandListResponse{
		Total: int32(total),
		Data:  categoryBrandResponse,
	}, nil
}

// 通过商品分类获取对应的商品品牌列表
func (g *GoodsServer) GetCategoryBrandList(c context.Context, r *proto.CategoryInfoRequest) (*proto.BrandListResponse, error) {
	category := new(model.Category)
	category.ID = r.Id
	result := DB.Where(category).First(category)
	if result.RowsAffected != 1 {
		return nil, status.Errorf(codes.NotFound, "Id:商品分类不存在")
	}

	var categoryBrandList []*model.GoodsCategoryBrand
	result = DB.Where(&model.GoodsCategoryBrand{CategoryID: category.ID}).Preload("Brands").Find(&categoryBrandList)
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}

	var brandInfoResponses []*proto.BrandInfoResponse
	for _, v := range categoryBrandList {
		brandInfoResponses = append(brandInfoResponses, &proto.BrandInfoResponse{
			Id:   v.Brands.ID,
			Name: v.Brands.Name,
			Logo: v.Brands.Logo,
		})
	}
	return &proto.BrandListResponse{
		Total: int32(result.RowsAffected),
		Data:  brandInfoResponses,
	}, nil
}

// 删除 商品分类-商品品牌 关系表
func (g *GoodsServer) DeleteCategoryBrand(c context.Context, r *proto.CategoryBrandRequest) (*emptypb.Empty, error) {
	goodsCategoryBrand := new(model.GoodsCategoryBrand)
	goodsCategoryBrand.ID = r.Id

	result := DB.Where(goodsCategoryBrand).First(goodsCategoryBrand)
	if result.RowsAffected != 1 {
		return nil, status.Errorf(codes.NotFound, "商品分类-商品品牌关系记录不存在")
	}

	result = DB.Delete(&goodsCategoryBrand)
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &empty.Empty{}, nil
}

// 更新 商品分类-商品品牌 关系表
func (g *GoodsServer) UpdateCategoryBrand(c context.Context, r *proto.CategoryBrandRequest) (*emptypb.Empty, error) {
	goodsCategoryBrand := new(model.GoodsCategoryBrand)
	goodsCategoryBrand.ID = r.Id

	result := DB.Where(goodsCategoryBrand).First(goodsCategoryBrand)
	if result.RowsAffected != 1 {
		return nil, status.Errorf(codes.NotFound, "商品分类-商品品牌关系不存在")
	}

	// 请求参数中包含零值字段也要更新
	result = DB.Model(goodsCategoryBrand).Updates(map[string]interface{}{
		"category_id": r.CategoryId,
		"brands_iD":   r.BrandId,
	})
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &empty.Empty{}, nil
}
